###
The Listview Widget displays a list of items, these items are for example a list of songs.
The Listview is just the view the items have to be stored in a store.


events: ['row-activated']
###

class tree.ui.Listview extends tree.ui.Widget
    constructor: (store) ->
        super
        if not store?
            throw new TypeError 'store must not be null'
            
        @store = store
        @htmlelem = document.createElement 'table'
        @htmlelem.className = 'tree-list-view';
        tr = document.createElement 'tr'
        @htmlelem.appendChild(tr)
        columns = store.get_model()
        for field of columns
            value = columns[field]
            if value != tree.ui.TYPES.object
                th = document.createElement 'th'
                tr.appendChild th
                th.innerHTML = field
            
        @store.connect 'changed', @on_changed
        @selected = null
    
    get_store: () ->
        @store
    
    update: () =>
        firstChild = @htmlelem.firstChild
        while @htmlelem.childNodes.length > 0
            @htmlelem.removeChild @htmlelem.firstChild
        
        @htmlelem.appendChild firstChild
        for i in [0..@store.length-1]
            tr = document.createElement 'tr'
            tr.className = 'tree-listview-cell'
            tr.index = i
            self = @
            tr.onclick = (event) ->
                if self.selected?
                    self.selected.className =  'tree-listview-cell'
               
                self.selected = @
                self.selected.className = 'tree-listview-cell-selected'
                
                self.emit 'row-activated', {index: @index}
            
            @htmlelem.appendChild tr
            rows = @store.get_values()[i]
            for row in rows
                td = document.createElement 'td'
                td.innerHTML = row
                tr.appendChild td
        @
    
    on_changed: (widget, evt, args) =>
        @update()
